<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>五子棋在线对战 - 注册</title>
    <link rel="stylesheet" href="styles.css">
</head>
<body>
    <div class="container">
        <div class="auth-container fade-in">
            <div class="auth-header">
                <div class="auth-logo">🔴⚫</div>
                <h1>五子棋在线对战</h1>
                <p><a href="login.html" class="auth-link">← 返回登录</a></p>
            </div>
            
            <form id="registerForm">
                <div class="form-group">
                    <input type="text" class="form-control" id="username" placeholder="设置账号（3-20个字符，字母数字下划线）" required>
                    <div class="error-message" id="username-error"></div>
                    <div class="success-message" id="username-success"></div>
                </div>
                
                <div class="form-group">
                    <input type="password" class="form-control" id="password" placeholder="设置密码（至少8位，包含字母和数字）" required>
                    <div class="error-message" id="password-error"></div>
                    <div id="password-strength" class="password-strength"></div>
                </div>
                
                <div class="form-group">
                    <input type="password" class="form-control" id="confirmPassword" placeholder="再次输入密码" required>
                    <div class="error-message" id="confirm-password-error"></div>
                </div>
                
                <div class="form-group">
                    <div class="error-message" id="form-error"></div>
                    <div class="success-message" id="form-success"></div>
                </div>
                
                <button type="submit" class="btn btn-success" style="width: 100%;" id="registerBtn" disabled>
                    <span id="registerBtnText">创建账号</span>
                    <span id="registerBtnLoading" class="loading hidden"></span>
                </button>
                
                <div class="auth-footer">
                    <p>已有账号？ <a href="login.html" class="auth-link">立即登录</a></p>
                </div>
            </form>
            
            <div class="auth-footer">
                <p>五子棋在线对战 - 随时随地与棋友切磋</p>
                <p>&copy; 2025 五子棋在线对战平台</p>
            </div>
        </div>
    </div>

    <script>
        let usernameAvailable = false;
        let passwordValid = false;
        let passwordConfirmed = false;
        
        // 检查是否已登录
        document.addEventListener('DOMContentLoaded', function() {
            const token = localStorage.getItem('token');
            if (token) {
                window.location.href = 'hall.html';
            }
        });

        // 注册表单处理
        document.getElementById('registerForm').addEventListener('submit', function(e) {
            e.preventDefault();
            
            // 清除之前的错误信息
            clearErrorMessages();
            
            // 获取表单数据
            const username = document.getElementById('username').value.trim();
            const password = document.getElementById('password').value;
            const confirmPassword = document.getElementById('confirmPassword').value;
            
            // 前端验证
            if (!validateForm(username, password, confirmPassword)) {
                return;
            }
            
            // 显示加载状态
            showLoading(true);
            
            // 调用注册API
            register(username, password);
        });

        // 表单验证
        function validateForm(username, password, confirmPassword) {
            let isValid = true;
            
            // 验证用户名
            if (!username) {
                showError('username-error', '请输入账号');
                isValid = false;
            } else if (!isValidUsername(username)) {
                showError('username-error', '用户名格式不正确');
                isValid = false;
            } else if (!usernameAvailable) {
                showError('username-error', '用户名不可用');
                isValid = false;
            }
            
            // 验证密码
            if (!password) {
                showError('password-error', '请输入密码');
                isValid = false;
            } else if (!isValidPassword(password)) {
                showError('password-error', '密码格式不正确');
                isValid = false;
            }
            
            // 验证确认密码
            if (!confirmPassword) {
                showError('confirm-password-error', '请再次输入密码');
                isValid = false;
            } else if (password !== confirmPassword) {
                showError('confirm-password-error', '两次密码输入不一致');
                isValid = false;
            }
            
            return isValid;
        }

        // 用户名格式验证
        function isValidUsername(username) {
            const regex = /^[a-zA-Z0-9_]{3,20}$/;
            return regex.test(username);
        }

        // 密码格式验证
        function isValidPassword(password) {
            // 至少8位，包含字母和数字
            const hasLetter = /[a-zA-Z]/.test(password);
            const hasNumber = /\d/.test(password);
            return password.length >= 8 && hasLetter && hasNumber;
        }

        // 密码强度检查
        function checkPasswordStrength(password) {
            let strength = 0;
            let feedback = '';
            
            if (password.length >= 8) strength++;
            if (/[a-z]/.test(password)) strength++;
            if (/[A-Z]/.test(password)) strength++;
            if (/\d/.test(password)) strength++;
            if (/[!@#$%^&*()_+\-=\[\]{};':"\\|,.<>\/?]/.test(password)) strength++;
            
            switch (strength) {
                case 0:
                case 1:
                    feedback = '<span style="color: #E74C3C;">密码强度：弱</span>';
                    break;
                case 2:
                case 3:
                    feedback = '<span style="color: #E67E22;">密码强度：中</span>';
                    break;
                case 4:
                case 5:
                    feedback = '<span style="color: #2ECC71;">密码强度：强</span>';
                    break;
            }
            
            return feedback;
        }

        // 注册API调用
        async function register(username, password) {
            try {
                const response = await fetch('/api/users/register', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({
                        username: username,
                        password: password
                    })
                });

                const result = await response.json();
                
                if (result.code === '1000') {
                    // 注册成功
                    showSuccess('注册成功！正在跳转到登录页面...');
                    
                    // 延迟跳转到登录页面
                    setTimeout(() => {
                        window.location.href = 'login.html';
                    }, 2000);
                } else {
                    // 注册失败
                    handleRegisterError(result.code, result.message);
                }
            } catch (error) {
                console.error('注册请求失败:', error);
                showError('form-error', '网络连接失败，请检查网络连接');
            } finally {
                showLoading(false);
            }
        }

        // 处理注册错误
        function handleRegisterError(code, message) {
            switch (code) {
                case '2001':
                    showError('username-error', '用户名已存在');
                    usernameAvailable = false;
                    updateSubmitButton();
                    break;
                case '2002':
                    showError('username-error', '用户名格式不正确');
                    break;
                case '2003':
                    showError('password-error', '密码格式不正确');
                    break;
                case '2004':
                    showError('form-error', '必填参数缺失');
                    break;
                default:
                    showError('form-error', message || '注册失败，请重试');
            }
        }

        // 检查用户名可用性（防抖）
        let usernameCheckTimeout;
        async function checkUsernameAvailability(username) {
            if (!isValidUsername(username)) {
                showError('username-error', '用户名格式：3-20个字符，只能包含字母、数字、下划线');
                usernameAvailable = false;
                updateSubmitButton();
                return;
            }
            
            try {
                // 这里可以调用一个检查用户名是否存在的API
                // 暂时模拟一个检查过程
                const response = await fetch(`/api/users/check-username?username=${encodeURIComponent(username)}`);
                
                if (response.ok) {
                    const result = await response.json();
                    if (result.code === '1000' && result.data.available) {
                        showSuccess('username-success', '✓ 用户名可用');
                        document.getElementById('username-error').textContent = '';
                        usernameAvailable = true;
                    } else {
                        showError('username-error', '用户名已被使用');
                        usernameAvailable = false;
                    }
                } else {
                    // 如果API不存在，暂时认为可用
                    showSuccess('username-success', '✓ 用户名可用');
                    document.getElementById('username-error').textContent = '';
                    usernameAvailable = true;
                }
            } catch (error) {
                // 网络错误时暂时认为可用
                showSuccess('username-success', '✓ 用户名可用');
                document.getElementById('username-error').textContent = '';
                usernameAvailable = true;
            }
            
            updateSubmitButton();
        }

        // 更新提交按钮状态
        function updateSubmitButton() {
            const button = document.getElementById('registerBtn');
            const canSubmit = usernameAvailable && passwordValid && passwordConfirmed;
            button.disabled = !canSubmit;
        }

        // 显示错误信息
        function showError(elementId, message) {
            const element = document.getElementById(elementId);
            if (element) {
                element.textContent = message;
                element.style.display = 'block';
            }
        }

        // 显示成功信息
        function showSuccess(elementId, message) {
            const element = document.getElementById(elementId);
            if (element) {
                element.innerHTML = message;
                element.style.display = 'block';
            }
        }

        // 清除错误信息
        function clearErrorMessages() {
            const errorElements = document.querySelectorAll('.error-message, .success-message');
            errorElements.forEach(el => {
                el.textContent = '';
                el.style.display = 'none';
            });
        }

        // 显示/隐藏加载状态
        function showLoading(isLoading) {
            const btn = document.getElementById('registerBtn');
            const btnText = document.getElementById('registerBtnText');
            const btnLoading = document.getElementById('registerBtnLoading');
            
            if (isLoading) {
                btn.disabled = true;
                btnText.style.display = 'none';
                btnLoading.classList.remove('hidden');
            } else {
                btn.disabled = !usernameAvailable || !passwordValid || !passwordConfirmed;
                btnText.style.display = 'inline';
                btnLoading.classList.add('hidden');
            }
        }

        // 用户名输入事件
        document.getElementById('username').addEventListener('input', function() {
            const username = this.value.trim();
            
            // 清除之前的检查结果
            document.getElementById('username-error').textContent = '';
            document.getElementById('username-success').textContent = '';
            usernameAvailable = false;
            updateSubmitButton();
            
            if (username.length >= 3) {
                // 防抖检查用户名
                clearTimeout(usernameCheckTimeout);
                usernameCheckTimeout = setTimeout(() => {
                    checkUsernameAvailability(username);
                }, 500);
            }
        });

        // 密码输入事件
        document.getElementById('password').addEventListener('input', function() {
            const password = this.value;
            
            // 显示密码强度
            const strengthEl = document.getElementById('password-strength');
            if (password) {
                strengthEl.innerHTML = checkPasswordStrength(password);
            } else {
                strengthEl.innerHTML = '';
            }
            
            // 验证密码格式
            passwordValid = isValidPassword(password);
            if (password && !passwordValid) {
                showError('password-error', '密码至少8位，包含字母和数字');
            } else {
                document.getElementById('password-error').textContent = '';
            }
            
            // 重新验证确认密码
            const confirmPassword = document.getElementById('confirmPassword').value;
            if (confirmPassword) {
                passwordConfirmed = password === confirmPassword;
                if (!passwordConfirmed) {
                    showError('confirm-password-error', '两次密码输入不一致');
                } else {
                    document.getElementById('confirm-password-error').textContent = '';
                }
            }
            
            updateSubmitButton();
        });

        // 确认密码输入事件
        document.getElementById('confirmPassword').addEventListener('input', function() {
            const password = document.getElementById('password').value;
            const confirmPassword = this.value;
            
            passwordConfirmed = password === confirmPassword && password.length > 0;
            if (confirmPassword && !passwordConfirmed) {
                showError('confirm-password-error', '两次密码输入不一致');
            } else {
                document.getElementById('confirm-password-error').textContent = '';
            }
            
            updateSubmitButton();
        });
    </script>

    <style>
        .password-strength {
            font-size: 14px;
            margin-top: 5px;
        }
    </style>
</body>
</html> 